//
//  THNetworkTools.swift
//  tripartiteTestDemo
//
//  Created by rimi on 2017/5/18.
//  Copyright © 2017年 rimi. All rights reserved.
//

import UIKit
import AFNetworking
// 接口数据回调闭包
typealias networkDataCallback = (_ callbackData:[String:Any]?, _ error: NSError?) -> ()
// 上传数据进度回调
typealias uploadImageCallback = (_ uploadProgress: Progress) -> ()

class THNetworkTools: AFHTTPSessionManager {

    // 单例类方法
    static let tools: THNetworkTools = {
        
        let instence = THNetworkTools(baseURL: nil)
        instence.responseSerializer.acceptableContentTypes?.insert("text/html")
        return instence
    }()
    
    // MARK: - 请求数据方法
    /// POST请求方法
    func request(cateG:String = "", method:String, action:String, sign:String = "",
                 params:[String:Any]? = nil,
                 finished:@escaping networkDataCallback) {
        // 获取登录状态
        let loginState = UserDefaults.standard.bool(forKey: kUserIsLoginKey)
        // 获得用户ID
        let sid = loginState ? (THUserLoinInfo.currentUser.sid ?? "") : ""
      
        // 配置参数
        let parameters: [String:Any] = ["g":cateG,
                          "m":method,
                          "a":action,
                          "sid":sid,
                          "params":jsonString(from: params),
                          "sign":sign,
                          "deviceInfo":getDeviceInfo(),
                          "channelId":"1000001",
                          "phoneType":"iphone"]

        // post请求数据
        post(kAPIUrl, parameters: parameters, progress: nil, success: { (_, data) in
            // 处理可选类型
            guard let dict = data as? [String:Any] else {
                return
            }
            // 判断服务器回调数据是否正常
            if dict["errCode"] as? Int == 0 {
                // 返回info对应的数据
                finished(dict["info"] as? [String:Any], nil)
            }else {
                finished(dict, NSError(domain: NSCocoaErrorDomain,
                                      code: dict["errCode"] as! Int,
                                      userInfo: ["errMessage":dict["errMessage"] ?? ""]))
            }
            
        }) { (_, error) in
            finished(nil, error as NSError)
        }
    }
    
    // MARK: - 图片上传
    /// 图片上传方法
    func uploadImage(cateG:String = "", method:String, action:String, sign:String = "",
                     images:[UIImage], imageKey:String, params:[String:Any]? = nil,
                     uploadProgress:uploadImageCallback? = nil,
                     finished:@escaping networkDataCallback) {
        // 获取登录状态
        let loginState = UserDefaults.standard.bool(forKey: kUserIsLoginKey)
        // 获得用户ID
        let sid = loginState ? (THUserLoinInfo.currentUser.sid ?? "") : ""
        
        // 配置参数
        let parameters = ["g":cateG,
                          "m":method,
                          "a":action,
                          "sid":sid,
                          "params":jsonString(from: params),
                          "sign":sign,
                          "deviceInfo":getDeviceInfo(),
                          "channelId":"1000001",
                          "phoneType":"iphone"]
        
        // post上传图片数据
        post(kAPIUrl, parameters: parameters, constructingBodyWith: { (formData) in
            
            // 循环转换和拼接图片数据
            for (i,img) in images.enumerated() {
                // 将图片转换为二进制
                guard let imageData = UIImageJPEGRepresentation(img, 0.5) else {
                    // 反馈错误消息
                    finished(nil, NSError(domain: NSCocoaErrorDomain,
                                          code: 1000,
                                          userInfo: ["errMessage":"图片\(imageKey)\(i)转换失败"]))
                    continue
                }
                // 拼接图片名称
                var imgName = imageKey
                if images.count > 1 {
                    imgName = "\(imageKey)\(i)"
                }
                
                // 拼接图片数据
                formData.appendPart(withFileData: imageData,
                                    name: imgName,
                                    fileName: "image.jpg",
                                    mimeType: "image/jpeg")
            }
            
        }, progress: { (pragress) in
            // 回调进度
            uploadProgress?(pragress)
        }, success: { (_, data) in

            // 处理可选类型
            guard let dict = data as? [String:Any] else {
                return
            }
            // 判断服务器回调数据是否正常
            if dict["errCode"] as? Int == 0 {
                // 返回info对应的数据
                finished(dict["info"] as? [String:Any], nil)
            }else {
                finished(dict, NSError(domain: NSCocoaErrorDomain,
                                       code: dict["errCode"] as! Int,
                                       userInfo: ["errMessage":dict["errMessage"] ?? ""]))
            }

        }) { (_, error) in
            finished(nil, error as NSError)
        }
    }
    
    // 将字典数据转换为json字符串
    func jsonString(from dict:[String: Any]?) -> String {
        // 将字典数据转换为json数据
        guard let jsonParams = try? JSONSerialization.data(withJSONObject: dict ?? ["":""], options: .prettyPrinted) else {
            return ""
        }
        return String(data: jsonParams, encoding: .utf8) ?? ""
    }
    
    // 获取设备信息
    //  model 终端型號
    //  version 终端操作系统版本
    //  manufacturer 终端品牌
    //  display    终端分辨率
    //  device     终端模组号码
    func getDeviceInfo() -> String {
        // 获得设备分辨率
        let display = "\(screenW*screenScale)x\(screenH*screenScale)"
        // 获得当前设备对象
        let device = UIDevice.current
        let deviceDict: [String : Any] = ["model":device.model,
                                          "version":device.systemVersion,
                                          "manufacturer":"Apple",
                                          "display":display,
                                          "device":""]
        // 将信息字典转换为json字符串
        return jsonString(from: deviceDict)
    }
}









